var module=angular.module("queryApp",[]);
//controller
module.controller("queryController",function($scope,$http,$timeout){
	$scope.refreshSelect=function(){
		$timeout(function(){
			$(".selectpicker").selectpicker('refresh');
		});
	}
	$scope.myObj = {
	        "background" : $scope.pageCfg.template.buttonColor,
	        "height": "100%", 
	        "width": "100%",
	        "border-radius": "10px",
	        "padding": "0px 10px"
	    }
	$scope.myObx = {
	        "background" : "white",
	        "height": "100%", 
	        "width": "100%",
	        "border-radius": "10px",
	        "padding": "0px 10px"
	    }
	//在ng-init中的进行初始化
	$scope.filter={};
	//瀑布流需要的参数
	
	var pagefall = 2;
	loading = false; 
	$scope.posts = []; 
	//下拉框默认显示数目
	$scope.selectedCol=9;
	//下拉列表显示可选数量
	$scope.numcol = [9, 18, 30];//123//456
	//echart 路径设置
	require.config({
	    paths: {
	        echarts: context+'/static/plugins/echarts',
	        theme:   context+'/static/plugins/echarts/theme'
	    }
	});
	$scope.loading=function(){
		var content='<div class="progress active">'+
		'<div class="progress-bar progress-bar-primary progress-bar-striped" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 100%">'
		'</div></div>';
		var jc=$.alert({
		    title: '加载中...',
		    content: content,
		    closeIcon: false,
		    confirmButton:false
		});
		return jc;
	}
	//取两数组的交集，a.b分别为两个数组
	var arrayIntersection = function(a, b){
		var result = new Array();
		for(var i=0;i<a.length;i++){
			for(var j=0;j<b.length;j++){
				if(a[i]==b[j]){
					result.push(a[i]);
				}
			}
		}

	  return result;
	}
	var cutfilter = function (data){
		//category抓取的数据内容
		var array=[];
		//filter抓取的数据内容
		var obj=[];
		//两数组交集内容
		var endarr=[];
		//category抓取数据放到数组里
		for(var i=0;i<data.category.length;i++){
			for(var j=0;j<data.category[i].data.length;j++){
				if(undefined==data.category[i].data[j].subData){
					array.push(data.category[i].data[j].Name);
				}else{
					for(var k=0;k<data.category[i].data[j].subData.length;k++){
						array.push(data.category[i].data[j].subData[k].Name);
					}
				}
				}
			}
		//filter抓取数据放到数组里
		for(var name in $scope.filter){
			for(var i=0;i<$scope.filter[name].length;i++){
				obj.push($scope.filter[name][i]);
			}
		}
		//将上面抓取出来的两个数组进行交集
		endarr=arrayIntersection(obj,array);
		//如果交集和filter不相等，就重新赋值
		if(arrayIntersection(obj,array).toString()!=obj.toString()){
//			console.log(arrayIntersection(obj,array).toString()==obj.toString());
			//重新赋值
			for(var k in $scope.filter){
				//将每个k下的数组和交集出来的数组进行交集，得出的值付给filter
				$scope.filter[k]=arrayIntersection($scope.filter[k],endarr);
			}
		}
	}

	
	$scope.getSelectCategory = function (){
		$scope.selectCategory = [];
		for ( var o in $scope.filter) {
			var arr = [];
			for ( var p in $scope.filter[o]) {
				var temp = {
						Name:$scope.filter[o][p],
						field:o
				}
				arr.push(temp)
			}
			$scope.selectCategory.push(arr);
		}
	}
	$scope.query = function (){
		if($scope.nowPage==null)$scope.nowPage=$scope.current;
		var jc=$scope.loading();
		$http({
			method:'POST',
			url:context+'/COQuery/coquery/ajax',
			data:{
				'queryWord':$scope.queryWord,
				'areaId':$scope.areaId,
				'filter':$scope.filter,
				'size':$scope.selectedCol,
				'nowPage':$scope.nowPage
				}
				
		}).success(function(data, status, headers, config){
			jc.close();
			$scope.category = data.category;
			cutfilter(data);
			$scope.getSelectCategory();	
			$scope.data = data.data.concat();//内容
			$scope.datafall = data.data.concat();//内容
			$scope.chartData = data.chartData;
			//刷新分页参数
			$scope.refreshPage(data.currentPage,data.toalNum,data.size);
			//加载瀑布流的数据
//			$scope.pushContent();
			//$scope.jsArray=data.jsArray;
//			angular.element("#load").show();
			pagefall=2;
			loading = false;
		});

	}

	//瀑布流查询
	$scope.pushContent =function() {
	 if (!loading) {
		 var jc=$scope.loading();
		 loading = true;
		 	 $scope.nowPage = pagefall;
				$http({
					method:'post',
					url:context+'/COQuery/coquery/ajax',
					data:{
						'queryWord':$scope.queryWord,
						'areaId':$scope.areaId,
						'filter':$scope.filter,
						'size':$scope.selectedCol,
						'nowPage':$scope.nowPage
						}	
				}).success(function(data, status, headers, config){
					jc.close();
					for ( var i = 0; i < data.data.length; i++) {
						$scope.datafall.push(data.data[i]);//内容
					}	
//					console.log($scope.data);
//					$scope.data = data.data;//内容
					console.log(data.data.length);
					if(data.data.length==0){
						loading = true;
					}else{
						loading = false;
					}
					 
				});
//				angular.element("#load").hide();
				pagefall++;	
			 }; 
		 
	}//end
	
	//刷新分页
	$scope.refreshPage = function(current,toalNum,size){
		//已知参数
		$scope.maxPage=8;
		$scope.current = current;
		$scope.toalNum = toalNum;
		$scope.size = size;
		//
		$scope.totalPage = Math.ceil($scope.toalNum/$scope.size)//总页数
		$scope.pre=($scope.current-1<1)?1:$scope.current-1;//上一页页码
		$scope.next=($scope.current+1>$scope.totalPage)?$scope.totalPage:$scope.current+1;//下一页页码
		//$scope.maxPage=($scope.totalPage>$scope.maxPage)?$scope.maxPage:$scope.totalPage;//当前页页码个数
		$scope._currentPage = Math.ceil($scope.current/$scope.maxPage);//当前页所在分页的页码
		$scope._startPage = ($scope._currentPage - 1)*$scope.maxPage + 1;//每页的开始页面
		var _maxPage = Math.ceil($scope.totalPage/$scope.maxPage);//最大页数
		$scope._firstPage = $scope._startPage;
		$scope.maxPageArr = [];
		//console.log("_startPage==="+_startPage)
		for(var i=0; i<$scope.maxPage;i++){
			if($scope._startPage<=$scope.totalPage){
				$scope.maxPageArr[i] = $scope._startPage;
				$scope._startPage++;
			}else{
				break;
			}
		}
		$scope._endPage = $scope._startPage;
	}//end

	//调用刷新分页
	$scope.refreshPage($scope.current,$scope.toalNum,$scope.size);
	//分类树查询
	$scope.catQuery=function(one,type){//导航
		$scope.nowPage = 1;//重新查询，页码设1.
		if("selected"==one.selected){
			one.selected="";
		}else{
			one.selected="selected";
		}
//		console.log("one"+one.selected);
		clickFilter(one,type);
		$scope.type = type;
		$scope.query();
		$scope.refreshSelect();
	}
	$scope.catQuery2=function(one){//导航
		$scope.nowPage = 1;//重新查询，页码设1.
		clickFilter2(one);
//		$scope.type = type;
		$scope.query();
		$scope.refreshSelect();
	}
	//树标签查询函数
	$scope.treeQuery=function(type){
		for(var i=0;i<type.data.length;i++){
			var one =type.data[i];			
			if($scope.filter[type.field].indexOf(one.Name)>=0){
				one.selected="selected";

			}else{
				one.selected="";
			}
		}
		$scope.type = type;
		$scope.nowPage=1;//重新查询，页码设1.
		$scope.query();
	};
	//筛选条件列表的增删方法
/*	var clickFilter=function(one,type){
		console.log("clickFilter")
		if(one.selected=="selected"){
			if($scope.filter[type.field]){
				var arr=$scope.filter[type.field];
				arr.push(one.Name);
				$scope.filter[type.field]=arr;
			}else{
				$scope.filter[type.field]=[one.Name];
			}
		}else{
			var arr=$scope.filter[type.field];
			for(var i=0;i<arr.length;i++){
				if(arr[i]==one.Name){
					arr.splice(i,1);
					break;
				}
			}
			$scope.filter[type.field]=arr;
		}
	}//end	
	*/
	var clickFilter=function(one,type){
//		console.log("clickFilter")
		if(one.selected=="selected"){
			if($scope.filter[type.field]){
				var arr=$scope.filter[type.field];
				arr.push(one.Name);
				$scope.filter[type.field]=arr;
			}else{
				$scope.filter[type.field]=[one.Name];
			}
		}else{
			var arr=$scope.filter[type.field];
			for(var i=0;i<arr.length;i++){
				if(arr[i]==one.Name){
					arr.splice(i,1);
					break;
				}
			}
			$scope.filter[type.field]=arr;
		}
	}//end	
	var clickFilter2=function(one){
			var arr=$scope.filter[one.field];
			for(var i=0;i<arr.length;i++){
				if(arr[i]==one.Name){
					arr.splice(i,1);
					break;
				}
			}
			$scope.filter[one.field]=arr;
		
	}//end	
	/**
	 * 避免下拉选帅选框，二级维度选择后，而无法取消。
	 * 
	 */
	$scope.changeFilter = function(){
//		console.log(JSON.stringify($scope.filter))
		for(var i in $scope.filter){
			var map = {};
			for ( var j = 0; j < $scope.filter[i].length; j++) {
				var key  = $scope.filter[i][j];
				if (!map[key]) {
					map[key] = 1;
				}else{
					map[key] ++;
				}
				if (map[key]%2==0) {
					$scope.filter[i].splice(j,1);
					var index = $scope.filter[i].indexOf(key);
					$scope.filter[i].splice(index,1);
				}
			}
		}
//		console.log(JSON.stringify($scope.filter))
	}//end

});

//翻页controller
module.controller("paginationCtrl",function($scope){

});

module.directive("ectooltip",function(){
	return {
		restrict:"E",
		template:'<div id="ecTooltip" class="ecTooltip"></div>',
		replace:true
	}
});
module.directive("charthome",function(){
	return {
		scope:{
			charthomedata:"="
		},
		restrict:"AE",
		templateUrl:context+"/static/app/template/tpl_charts.html",
		replace:true,
		link:function(scope,element,attr){
			scope.$watch('charthomedata', function(newValue, oldValue) {
				 checklinkageChart(newValue);
			});
			 addChart();
			 function checklinkageChart(charthomedata){
					for ( var i = 0; i < charthomedata.length; i++) {
						var chart = charthomedata[i];
						var div_id = chart.type +"_"+ chart.chartId;
						if (chart.linkage == "true") {
							element.find("#"+div_id).html("");
							if ("pie" == chart.type || "wordCloud" == chart.type) {
								echarts.createChart(scope,chart.type,chart.name,chart.dimension[0],element.find("#"+div_id)[0]);
							}else{
								echarts.createChart(scope,chart.type,chart.name,chart.dimension,element.find("#"+div_id)[0]);
							}
						}
					}
		
			}//
			
			function updateLinkageDate(newData,oldData){
				var tempArr = [];
				for ( var i = 0; i < newData.length; i++) {
					if (newData[i].linkage) {//更新
						tempArr.push(newData[i]);
					}else{
						var id = newData[i].chartId;
						for ( var j = 0; j < oldData.length; j++) {
							var id2 = oldData[j].chartId;
							if (id == id2) {
								tempArr.push(oldData[j]);
							}
						}
						
					}
				}
//				scope.charthomedata = tempArr;
				
			}//
			
			function addChart(){
				element.carousel('pause');//取消自动轮播
				var hiddenParents = element.parents(":hidden");//所有隐藏父元素
				var noneParents = [];//记录css 属性为display none 的节点
				for ( var i = 0; i < hiddenParents.length; i++) {
					var nodeDisplay = $(hiddenParents[i]).css("display");
					if (nodeDisplay == "none") {
						noneParents.push($(hiddenParents[i]));
						$(hiddenParents[i]).css("display","block");//设为显示一边插入图表
					}
				}
				var widthParent = element.parent().width();
				//设置id防止同一页面插入多个图表组件id污染
				var pid = element.parent().attr('id');
				var newId = element.attr('id',pid+"_chart").attr('id');
				element.find('a').attr('href','#'+newId);
				//加载图表
//				console.log(JSON.stringify(scope.charthomedata))
//				console.log(scope.charthomedata);
				if(!scope.charthomedata || scope.charthomedata.length==0){
					var chartDIV = '<div class="item active" style="font-size: 24px; text-align: center; top: 45%;margin-left: 10%;padding-top:15px;">您没有配置图表 </div>';
					element.find("#chart_DIV").html(chartDIV);
				}else {
					scope.p_width =element.find("#chart_DIV").width()*0.86;
					var p_height =element.find("#chart_DIV").height();
					scope.pageChatData = chartLayout(scope.p_width,p_height);
					insertChart_page(scope.p_width, p_height, scope.pageChatData)
					
				}
			/*	if(blockContext=="none"){
					$("#context").css("display","none");
				}
				if(block=="none"){//如果是隐藏将其还原。
					element.parent().css("display","none");
				}*/
				for ( var i = 0; i < noneParents.length; i++) {//隐藏元素还原
					noneParents[i].css("display","none");
				}
				
			}//end
			
			/*
			 * 分页图表，数据整理
			 */
			function chartLayout(p_width,p_height){
				var n = Math.floor(p_width/p_height);	//默认拆分比
				n = (n<1)?1:n;
//				console.log(n);//				var c_size = 0;//一页几张图
				var c_n = 0;//实际每页份数累计(实际拆分比)
				var page_chart =[];//每页的图表
				var size_chart =[];//返回值json数组每页的拆分比例与图表数据
				var json_chart = {};//一页的数据
				for(var i=0; i<scope.charthomedata.length;i++){
					var chart = scope.charthomedata[i];
					var src=scope.charthomedata[i].src;
					var chartType = chart.type;
					if ("pie"==chartType || n==1) {
//						console.log(JSON.stringify(chart.dimension))
						if (c_n+1<=n) {
							c_n++;
							page_chart.push(chart);
							if(i==scope.charthomedata.length-1){
								json_chart = {n:c_n,charts:page_chart};
								size_chart.push(json_chart);
								return size_chart;
							}
						}else{
							json_chart = {n:c_n,charts:page_chart};
							size_chart.push(json_chart);
							page_chart = [];
							page_chart.push(chart);
							c_n = 1;
							if(i==scope.charthomedata.length-1){
								 json_chart = {n:c_n,charts:page_chart};
								size_chart.push(json_chart);
								return size_chart;
							}
						}
					}else{
						if(c_n+2 <= n){
							c_n = c_n + 2;
							page_chart.push(chart);
							if(i==scope.charthomedata.length-1){
								 json_chart = {n:c_n,charts:page_chart};
								size_chart.push(json_chart);
								return size_chart;
							}
						}else{
							json_chart = {n:c_n,charts:page_chart};
							size_chart.push(json_chart);
							page_chart = [];
							page_chart.push(chart);
							c_n = 2;
							if(i==scope.charthomedata.length-1){
								json_chart = {n:c_n,charts:page_chart};
								size_chart.push(json_chart);
								return size_chart;
							}
						}
					}
					
				}
				
			}
			
			
			
			//图表插入
			function insertChart_page(p_width,p_height,size_chart){
				var x = Math.floor(p_width/p_height);	//默认拆分比
				x = (x<1)?1:x;
//				console.log(x);
				element.find("#chart_DIV").html("");
				
				for ( var i = 0; i < size_chart.length; i++) {
//					console.log(size_chart.length);
					var pageChartData = size_chart[i];
//					console.log(pageChartData.length)
					var n = pageChartData.n;
					var chartDIVs = '<div id="chartPage_'+i+'" class="item active" style="width:'+p_width+'px;height:'+p_height+'px;margin-left: 6%">';//;   
					for ( var j = 0; j < pageChartData.charts.length; j++) {
						var c_chart = pageChartData.charts[j];
						var c_div_id = c_chart.type +"_"+ c_chart.chartId;
						var w;
						if ("pie" == c_chart.type || x==1) {
							w = p_width/n;
						}else{
							w = p_width/n*2;
						}
						if(c_chart.type=="outside"){
						chartDIVs =chartDIVs+'<div id="'+c_div_id+'" >'+'<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="yes" style="float:left; width:'+w+'px;height:'+p_height+'px;" src='+c_chart.src+'>'+'</div>';	
						}else{					
						chartDIVs +=  '<div id="'+c_div_id+'" style="float:left; width:'+w+'px;height:'+p_height+'px;"></div>';	
						}
					}
					chartDIVs += '</div>';//active
					element.find("#chart_DIV").children().attr("class","item");
					element.find("#chart_DIV").append(chartDIVs);
					for( var j = 0; j < pageChartData.charts.length; j++){
						var c_chart = pageChartData.charts[j];
						var c_div_id = c_chart.type +"_"+ c_chart.chartId;
						if ("pie" == c_chart.type || "wordCloud"==c_chart.type) {
							echarts.createChart(scope,c_chart.type,c_chart.name,c_chart.dimension[0],element.find("#"+c_div_id)[0]);
						}else if("outside"==c_chart.type){
					/*		var ChartOutside='<div id=chartPage_2  class="item active" style="width:'+p_width+'px;height:'+p_height+'px;margin-left: 6%">'+
							'<img src='+c_chart.src+'>'+'</div>';
							element.find("#chart_DIV").append(ChartOutside);*/
						}else{
							echarts.createChart(scope,c_chart.type,c_chart.name,c_chart.dimension,element.find("#"+c_div_id)[0]);
						}
					}
//					if (i==size_chart.length-1) {////默认显示最后一页
//						initDimension(size_chart[i]);
//					}
				}
				//默认显示第一页
				element.find("#chart_DIV").children().attr("class","item");
			    element.find("#chart_DIV").children(":first").attr("class","item active");
//				initDimension(size_chart[0]);
			}//
			
			
			
			
			/*
			 * 初始化维度
			 */
			function initDimension(oneSizeChart){
//				console.log(oneSizeChart)
				element.find("#dimension_charts").html("");
				var n = oneSizeChart.n;
				var w = scope.p_width*0.07;//left定位距离
				for ( var i = 0; i < oneSizeChart.charts.length; i++) {
					var chart = oneSizeChart.charts[i];
					var chartId = chart.type+"_"+chart.chartId;
					if (i>0) {
						if ("pie"==oneSizeChart.charts[i-1].type) {//当前图表前面的所有图宽度累加
							w += scope.p_width/n;
						}else{
							w += scope.p_width/n*2;
						}
					}
					var str = '<div class="form-group"   style="position: absolute;left: '+w+'px;z-index:2;">';
					str += '<label class="dis-label">维度：</label>';
					str += '<select class="form-control dis-sel">';
					for ( var j = 0; j < chart.dimension.length; j++) {
						var dimension = chart.dimension[j];
						var val = chartId+"&"+dimension.cdId
						str += '<option value="'+val+'">'+dimension.name+'</option>';
					}
					str += ' </select> </div>';
					if (chart.type=="pie" || chart.type=="wordCloud") {
						element.find("#dimension_charts").append(str);
					}
				}
				change_dimension();//绑定事件
			}
			/* 绑定事件
			 * 维度切换跟新图表
			 */
			function change_dimension(){
				element.find("#dimension_charts select").on("change",function(){
					var c_d = this.value.split("&");
					var cId = c_d[0].split("_");
//					var c_data = JSON.parse(scope.charthomedata);
					for ( var i = 0; i < scope.charthomedata.length; i++) {
						var chart = scope.charthomedata[i];
						if (cId[1]==chart.chartId) {
							for ( var j = 0; j < chart.dimension.length; j++) {
								if (c_d[1]==chart.dimension[j].cdId) {
									var selectDIV = element.find("#"+c_d[0]);
									var chartType = chart.type;
									var chartName = chart.name;
									echarts.createChart(scope,chartType,chartName,chart.dimension[j],selectDIV[0]);
								}
							}
						}
					}
				});
				
			}
			
			
			/*
			 * 切换图表更新维度
			 */
			scope.update_chart = function(v){
				var selectDIV_id = element.find("#chart_DIV div.active").attr('id');
				var splitId = selectDIV_id.split("_");
				var index;
				if ("pre"==v) {
					if (splitId[1]==0) {
						index = scope.pageChatData.length-1;
					}else{
						index = parseInt(splitId[1])-1;
					}
				}else if ("next"==v) {
					if (splitId[1]==scope.pageChatData.length-1) {
						index = 0;
					} else {
						index =  parseInt(splitId[1])+1;
					}
				}
//				initDimension(scope.pageChatData[index]);
			}//end
			
			//屏幕缩放重新加载图表
			$(window).resize(function(){
					addChart();
			});
			
			
			
			//监听鼠标位置
			scope.mousemove = function(event){
				scope.x = event.pageX;
				scope.y = event.pageY;
			}
			//鼠标离开组件隐藏提示框
			scope.closeEcTooltip = function(){
				$("#ecTooltip").css("display","none");
			}
			
	
		},
		controller:function($scope,$http){
			
//			$scope.charthomedata = JSON.parse($scope.charthomedata);
		}
	}
});


//指令directive
//分类树
module.directive("category",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_category.html",
		replace:true,
	
	}
});

module.service('FindArea',['$rootScope','$http',function($rootScope,$http){
	var service={
			find:function(){
				//请求
				return $http({
					url:context+'/area/findArea'
				});
			}
	};
	return service;
}]);

module.directive("navigation",['FindArea',function(FindArea){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_navigation.html",
		replace:true,
		link:function(scope,element,attr){
			FindArea.find();
		},
		controller:function($scope,$http){
			$scope.naQuery=function($event){
				$scope.areanameid=$event.target.id;
				$scope._this = $(this);			
				for ( var i = 0; i < $scope.areas.length; i++){
					var areaId = $scope.areas[i].areaId;
					if(areaId==$scope.areanameid){
						areaId.selected="selected"
					}else{
						areaId.selected="";
					}
					}			
				var jc=$scope.loading();
			}
		}
	}
}]);
module.directive("navigationy",['FindArea',function(FindArea){
	return{
	//	scope:{},
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_navigationy.html",
		replace:true,
		link:function(scope,element,attr){
			if(element.width()>element.height()){
				element.find(".sidebar-menu").addClass("smenu")
			}else{
				element.find(".sidebar-menu").addClass("xmenu")
			}
			FindArea.find().success(function(data, status, headers, config){
				scope.areas = data.data;
			});
		},
		controller:function($scope,$http){
			$scope.naQuery=function($event){
				$scope.areanameid=$event.target.id;
//				console.log("----------");
//				console.log($event.target.id);
				$scope._this = $(this);			
				for ( var i = 0; i < $scope.areas.length; i++){
					var areaId = $scope.areas[i].areaId;
//					console.log(areaId);
					if(areaId==$scope.areanameid){
						areaId.selected="selected"
					}else{
						areaId.selected="";
					}
					}
				var jc=$scope.loading();
				/*$http({
					method:'post',
					url:context+'/COQuery/coquery',
					data:{
						'queryWord':$scope.queryWord,
						'areaId':areanameid,
						'size':$scope.selectedCol,
						'nowPage':$scope.nowPage
						}
						
				}).success(function(data, status, headers, config){
//					$scope.category = data.category;  暂不刷新导航
					$scope.data = data.data;//内容
					//刷新分页参数
					$scope.refreshPage(data.currentPage,data.toalNum,data.size);
					//$scope.jsArray=data.jsArray;
					jc.close();
				});*/
			}
		}
	}
}]);
//label筛选栏
module.directive("labelcate",function(){
	return {
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_labelcate.html",
		transclude:true,				//css文件依赖于labelcate标签，所以不能使用replace
		controller:function($scope){
			$scope.clearFilter=function(cat){
				//清空filter中的内容
				$scope.filter[cat.field]=[];
				//将select信息置空
				for(var i=0;i<cat.data.length;i++){
					cat.data[i].selected=false;
				}
				    $scope.query();
			};
		}
	}
});
//工具栏组件
module.directive("toolbar",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_toolbar.html",
		transclude:true,
	}
});

//组件
//hit内容区域
module.directive("hitcontent",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_hit_content.html",
		replace:true,
		controller:function($scope,$http){
			//分页中的 ...按钮，重置页码
			$scope.resetPage = function(v){
				if (v=="pre") {
					$scope._currentPage = $scope._currentPage-1;
				}else if(v=="next"){
					$scope._currentPage = $scope._currentPage+1;
				}
				$scope._startPage = ($scope._currentPage-1)*$scope.maxPage+1;//开始
				$scope._firstPage = $scope._startPage;
				$scope.maxPageArr=[];
				for(var i=0;i<$scope.maxPage;i++){
					if($scope._startPage<=$scope.totalPage){
						$scope.maxPageArr[i] = $scope._startPage;
						$scope._startPage++;
					}else{
						 break;
					}
				}
			}
			//翻页
			$scope.page = function (p){
				$scope.nowPage = p;
				$scope.query();
			}
		}
	}
});

//组件
//单例图模态框
module.directive("modelchart",function(){
//	console.log("modelchart")
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/m_chart.html",
		replace:true,
		controller:function($scope,$http){
			$scope.create_chart = function(){
//				console.log($scope.field_name)
				var display = "";
				if($scope.field_name.display_name==''){
					 display = $scope.field_name.name;
				}else{
					 display = $scope.field_name.display_name;
				}
//				$scope.compareData
				var temp = {
						name:display,
						val:$scope.compareData[$scope.field_name.name]
				};
				$http({
					method:'post',
					url:context+'/COQuery/coquery/singtonChart',
					data:{
//						'queryWord':$scope.queryWord,
						'areaId':$scope.areaId,
//						'filter':$scope.filter,
						'aggField':$scope.field_name.name,
						'compareData':$scope.compareData
						}
						
				}).success(function(data, status, headers, config){
					if (data=="") {
						$("#myModal #model_chart").html("<div class='sington-chart-empty'>您选择的字段有误！！！</div>")
					}else{
						$("#myModal #model_chart").html('');
						singtone.createChart($scope.chart_type,temp,data,$("#myModal #model_chart")[0]);
					}
					
				});
			}
		}
	}
});

//hit表格形式
module.directive("hittable",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_hit_table.html",
		replace:true,
		controller:function($scope,$http){
//			angular.element("#selectTable").bind("change",function(){
//				$scope.query();
//			});
			 $scope.change = function(){
				 $scope.query();
				  }
			//分页中的 ...按钮，重置页码
			$scope.resetPage = function(v){
				if (v=="pre") {
					$scope._currentPage = $scope._currentPage-1;
				}else if(v=="next"){
					$scope._currentPage = $scope._currentPage+1;
				}
				$scope._startPage = ($scope._currentPage-1)*$scope.maxPage+1;//开始
				$scope._firstPage = $scope._startPage;
				$scope.maxPageArr=[];
				for(var i=0;i<$scope.maxPage;i++){
					if($scope._startPage<=$scope.totalPage){
						$scope.maxPageArr[i] = $scope._startPage;
						$scope._startPage++;
					}else{
						 break;
					}
				}
			}
			$scope.pageCfg.fields;
			//翻页
			$scope.page = function (p){
				$scope.nowPage = p;
				//点击翻页按钮，变颜色
				$(".pagination>li>a").css("color","#23527c");
				$(".pagination>li>a").css("background-color","transparent");
				$(".pagination>li>a").css("border-color","#ddd");
				$("#"+p).children().css("background-color",$scope.pageCfg.template.buttonColor);
				$("#"+p).children().css("border-color",$scope.pageCfg.template.buttonColor);
				$("#"+p).children().css("color","white");
				if($scope.nowPage==null)$scope.nowPage=$scope.current;
				var jc=$scope.loading();
				$http({
					method:'post',
					url:context+'/COQuery/coquery/ajax',
					data:{
						'queryWord':$scope.queryWord,
						'areaId':$scope.areaId,
						'filter':$scope.filter,
						'size':$scope.selectedCol,
						'nowPage':$scope.nowPage
						}
						
				}).success(function(data, status, headers, config){
//					$scope.category = data.category;  暂不刷新导航
					$scope.data = data.data;//内容					
					//刷新分页参数
					$scope.refreshPage(data.currentPage,data.toalNum,data.size);
					//$scope.jsArray=data.jsArray;
					jc.close();
				});
			
			}
		}
	}
});
//hit瀑布形式
module.directive("hitfall",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_hit_fall.html",
		replace:true,
		controller:function($scope,$http){
			$scope.getOneData = function(data){
				$scope.compareData = data;
				$http({
					method:'post',
					url:context+'/COQuery/coquery/allFields',
					data:{
						'areaId':$scope.areaId
						}	
				}).success(function(data, status, headers, config){
						$("#myModal #model_chart").html('');
						$scope.allField = [];
						for ( var i = 0; i < data.length; i++) {
							if (data[i].type=="integer" || 
								data[i].type=="float" || 
								data[i].type=="double") {
								$scope.allField.push(data[i])
							}
						}
				});
			}
//			$(document).ready(function (){
//			       var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度)
//			       var nScrollTop = 0;   //滚动到的当前位置
//			       var nDivHight = $("#fall").height();
//			       $("#fall").scroll(function(){
//			         nScrollHight = $(this)[0].scrollHeight;
//			         nScrollTop = $(this)[0].scrollTop;
//			　　　　　var paddingBottom = parseInt( $(this).css('padding-bottom') ),paddingTop = parseInt( $(this).css('padding-top') );
//			         if(nScrollTop + paddingBottom + paddingTop + nDivHight >= nScrollHight)
////			           alert("滚动条到底部了");
//			         $scope.pushContent();
//			         });
//			     });
			}
		}
});
//suggestion
module.directive("suggestion",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_suggestion.html",
		replace:true,
		controller:function($scope,$http){}
		}
});
//search
module.directive("search",function(){
	return{
		restrict:"E",
		templateUrl:context+"/static/app/template/tpl_search.html",
		replace:true,
		controller:function($scope,$http){
			 $scope.myKeyup = function(e){
		            var keycode = window.event?e.keyCode:e.which;
		            if(keycode==13){
		                $scope.formSubmit();
		            }
		        };
			//修改layout提交方法
			$scope.formSubmit=function(){
				var jc =$scope.loading();
				$http({
					method:'post',
					url:context+'/COQuery/coqueryFrom',
					data:{
						queryWord:$scope.queryWord,
						areaId:$scope.areaId,
						size:$scope.selectedCol,
						nowPage:1
					}
				}).success(function(data){
					$scope.category = data.category;  //暂不刷新导航
					$scope.data = data.data.concat();//内容
					$scope.datafall = data.data.concat();//内容
					$scope.chartData = data.chartData;
//					console.log($scope.chartData)
					//刷新分页参数
					$scope.refreshPage(data.currentPage,data.toalNum,data.size);
					//加载瀑布流的数据
//					$scope.pushContent();
					//$scope.jsArray=data.jsArray;
//					angular.element("#load").show();
					pagefall=2;
					loading = false;
					jc.close();
				});
			}
//			{{(pageCfg.template.fontColor==''||pageCfg.template.fontColor==undefined)?'#eeeeee':pageCfg.template.fontColor}}
//			 $scope.div1Bg = '#ffffff';
//			 $scope.div2Bg = '#F53676';
//			$scope.togglebutton=function(){
//				$scope.visible = !$scope.visible;
//				 $scope.div1Bg = $scope.div2Bg;
//			}
			$scope.disabledTable = true; 
			$scope.disabledFall = false; 
			$scope.div2Bg = ($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.buttonColor;
			$scope.div1Bg =($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.fontColor;
			$scope.table = function(){  
				 $scope.div1Bg =($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.fontColor;
				 $scope.div2Bg =($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.buttonColor;
				 $scope.visible = !$scope.visible;
				 $scope.disabledTable = true; 
				 $scope.disabledFall = false; 
				 return false;
			}; 
			$scope.fall = function(){  
				 $scope.div2Bg =($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.fontColor;
				 $scope.div1Bg =($scope.pageCfg.template.fontColor==''||$scope.pageCfg.template.fontColor==undefined)?'#eeeeee':$scope.pageCfg.template.buttonColor;
				 $scope.visible = !$scope.visible;
				 $scope.disabledTable = false; 
				 $scope.disabledFall = true; 
				 return false;
				}; 
		}
		}
});


//背景图片
module.directive("background",function(){
	return{
		restrict:"A",
		link:function(scope,element,attr){
			var imgRepeat=scope.pageCfg.template.imgRepeat;
			element.css("background-image","url("+imgPath+scope.pageCfg.background.url+")");
			if(imgRepeat=="repeat"){
				element.css("background-repeat",imgRepeat);
			}else if(imgRepeat="tensile"){
				element.addClass(imgRepeat);
			}
		}
	}
});
//滚动条组件
//module.directive("navscroll",function(){
//	return{
//		restrict:"A",
//		link:function($scope,ele,attr,ctrl){
//	
//			if(ele.width()>ele.height()){
//				ele.mCustomScrollbar({
//					theme:"minimal-dark",
//					axis:"x",
//					advanced:{autoExpandHorizontalScroll:true}
//				});
//			}else{
//				ele.mCustomScrollbar({
//					axis:"y",
//					theme:"minimal-dark",	
//					
//					advanced:{autoExpandHorizontalScroll:true}
//				});
//			}
//			}
//		}
//});
module.directive("nicescroll",function(){
	return{
		restrict:"A",
		link:function($scope,ele,attr,ctrl){
			//导航栏判断横向和竖向滚动条
			if(attr.nav=="true"){
				if(ele.width()>ele.height()){
					attr.axis="x"
				}else{
					attr.axis="y"
				}
			}
			ele.mCustomScrollbar({
				theme:"minimal-dark",
				scrollEasing:"easeOutCirc",
				mouseWheel:true,
				autoDraggerLength:true,
				axis:(attr.axis==undefined||attr.axis==""?"y":attr.axis),
				scrollInertia:(attr.ina==undefined||attr.ina==""?1000:parseInt(attr.ina)),//滚动条惯性
				autoDraggerLength:true,
				mouseWheelPixels:(attr.pls==undefined||attr.pls==""?300:parseInt(attr.pls)),//滚动条滚动的像素数目
				advanced:{autoExpandHorizontalScroll:true},
//				scrollInertia:5,
//				mouseWheelPixels:50,
//				scrollButtons:{
//	                scrollType:'pixels',
//	                enable:true,
//	                scrollAmount:40
//	            },
				callbacks:{
					//判断瀑布流滚动条滚动到底加载数据的
					onTotalScroll:function(){
						if(attr.fall=="true"){
							$scope.pushContent();
						}
					},
					onTotalScrollOffset:0,
					whileScrolling:false,
					whileScrollingInterval:10
				}
			});
		}
	}
});
//module.directive("nicescrolly",function(){
//	return{
//		restrict:"A",
//		link:function($scope,ele,attr,ctrl){
//			ele.mCustomScrollbar({
//				theme:"minimal-dark",
//				axis:"y",
//				scrollInertia:1000,
//				autoDraggerLength:true,
//				mouseWheelPixels:100,
//				advanced:{autoExpandHorizontalScroll:true}
//			});
//		}
//	}
//});
////单独的瀑布里滚动条组件
//module.directive("nicescrollfall",function(){
//	return{
//		restrict:"A",
//		link:function($scope,ele,attr,ctrl){
//			ele.mCustomScrollbar({
//				theme:"minimal-dark",
//				set_width:false,
//				set_height:false,
//				horizontalScroll:false,
//				callbacks:{
//					onTotalScroll:function(){
//						if(attr.id=="fall"){
//							$scope.pushContent();
//						}
//					},
//					onTotalScrollOffset:0,
//					whileScrolling:false,
//					whileScrollingInterval:10
//				}
//			});
//		}
//	}
//});
//过滤器
module.filter('trustHtml', function($sce) {
	return function(input) {
		if(input && (typeof input=='string')&&input.constructor==String){
			return $sce.trustAsHtml(input);
		}
		if(input && (typeof input=='object')&&input.constructor==Array){
			return $sce.trustAsHtml(input.join("/"));
		}

	}
});

module.filter("em",function(){
	return function(input) {
		if (input && typeof(input) == "string") {
			var e = 1;
			var m = 1;
			while(e>0 || m>0){
				e = input.indexOf("<em>");
				m = input.indexOf("</em>");
				input = input.replace('<em>','');
				input = input.replace('</em>','');
			}
		}
		return input;
	}
});
module.directive('hover',[function(){
    return {
        restrict:'A',
        link:function(scope,ele,attrs){
            ele.bind('mouseover',function(){
               ele.toggleClass('active');
            });
            ele.bind('mouseout',function(){
                ele.toggleClass('active');
            });
        }
    }
}]);
//niceselect控件
module.directive('niceselect',['$timeout',function($timeout){
    return {
        link: function(scope,element,attr){
        	//待ng-repeat结束后，加载selectpicker
        	$timeout(function(){
            	element.selectpicker('refresh');
        	});
        	//onchange函数，当select值改变时，提交treeQuery方法，并刷新selectpicker
        	element.bind("change",function(){
        		//when click,remove dropdown-menu,because it is body'element ,it will not refresh.
        		//there is no more good idea
        		element.closest("body").find(".dropdown-menu").remove();
            	scope.$apply("treeQuery(x)");
            });
        }
    }
}])
